package org.example.gateway.session;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.util.concurrent.Callable;

public class SessionServer implements Callable<Channel> {

    private final Logger logger = LoggerFactory.getLogger(SessionServer.class);

    private final EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    private final EventLoopGroup workerGroup = new NioEventLoopGroup();

    private Channel channel;
    @Override
    public Channel call() throws Exception {
        ChannelFuture channelFuture = null;

        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childHandler(new SessionChannelInitializer());

            channelFuture = bootstrap.bind(new InetSocketAddress(7397)).syncUninterruptibly();

            this.channel = channelFuture.channel();
        } catch (Exception e) {
            logger.error("Socket server start error. {}", e.getMessage(), e);
        } finally {
            if (channelFuture != null && channelFuture.isSuccess()) {
                logger.info("Socket server start success.");
            } else {
                logger.error("Socket server start error.");
            }

        }
        return channel;
    }
}
